using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Models;
using Services;
using Constants;
using Microsoft.EntityFrameworkCore;
using Data;

namespace Controllers
{
    /// <summary>
    /// 用户管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IPermissionService _permissionService;
        private readonly ApplicationDbContext _dbContext;

        /// <summary>
        /// 构造函数，注入所需服务
        /// </summary>
        public UsersController(
            IPermissionService permissionService,
            ApplicationDbContext dbContext)
        {
            _permissionService = permissionService;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 获取所有用户列表
        /// </summary>
        /// <returns>用户列表</returns>
        [HttpGet]
        [Authorize(Policy = $"{PermissionConstants.UsersPrefix}View")] // 需要查看用户的权限
        public async Task<IActionResult> GetUsers()
        {
            var users = await _dbContext.AppUsers
                .Include(u => u.UserRoles) // 包含用户角色关联
                .ThenInclude(ur => ur.Role) // 包含角色信息
                .ToListAsync();
                
            return Ok(users);
        }

        /// <summary>
        /// 创建新用户
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>创建的用户信息</returns>
        [HttpPost]
        [Authorize(Policy = $"{PermissionConstants.UsersPrefix}Create")] // 需要创建用户的权限
        public async Task<IActionResult> CreateUser([FromBody] User user)
        {
            _dbContext.AppUsers.Add(user);
            await _dbContext.SaveChangesAsync();
            return Ok(user);
        }
    }
} 